const crypto = require('crypto')
const jwt = require('jwt-simple')
const {
  loginConfig,
  tokenExp
} = require('../../utils/constants.js')

const db = uniCloud.database()

async function loginMP(event){
	//  AppId: 'wx00c5442b09058a1a', //微信小程序AppId
	//  AppSecret: 'dc0e8a80afadb472f08d2fd97dbffeb1' //微信小程序AppSecret
	let data = {
	  appid: "wx00c5442b09058a1a",
	  secret: "dc0e8a80afadb472f08d2fd97dbffeb1",
	  js_code: event.code,
	  grant_type: 'authorization_code'
	}
	
	const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
	  method: 'GET',
	  data,
	  dataType: 'json'
	})
	
	const success = res.status === 200 && res.data && res.data.openid
	if (!success) {
	  return {
	    status: -1,
	    msg: '微信登录失败'
	  }
	}
	
	const {
	  openid,
	} = res.data
	
	let userInfo = {
	    openid
	  }
	
	  let tokenSecret = crypto.randomBytes(16).toString('hex'),
		  token = jwt.encode(userInfo, tokenSecret)
	
	  const userInDB = await db.collection('usermp').where({
	    openid
	  }).get()
	
	  let userUpdateResult
	  if (userInDB.data && userInDB.data.length === 0) {
	    userUpdateResult = await db.collection('usermp').add({
	      ...userInfo,
	      tokenSecret,
	      exp: Date.now() + tokenExp
	    })
	  } else {
	    userUpdateResult = await db.collection('usermp').doc(userInDB.data[0]._id).set({
	      ...userInfo,
	      tokenSecret,
	      exp: Date.now() + tokenExp
	    })
	  }
	
	  if (userUpdateResult.id || userUpdateResult.affectedDocs === 1) {
	    return {
	      status: 0,
	      token,
		  openid,
	      msg: '登录成功'
	    }
	  }
	
	  return {
	    status: -1,
	    msg: '微信登录失败'
	  }
}

exports.main = loginMP;